package com.ttn.login;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ttn.entities.User;
import com.ttn.login.LoginController;
import com.ttn.user.bus.UserService;
import com.ttn.util.LanguageBean;
import com.ttn.util.WebUserPreferences;

@Controller
public class LoginController {
	
	
	
	private Logger LOG = Logger.getLogger(LoginController.class);

	@Autowired
	private WebUserPreferences webUserPref;

	@Autowired
	private LanguageBean languageBean;

	@Autowired
	private UserService userService;

	@RequestMapping("/**/login")
	public String processLoginRequest(HttpServletRequest request,
			HttpServletResponse response) {
		if (request.getParameter("j_password") != null
				&& request.getParameter("j_username") != null) {
			String password = request.getParameter("j_password");
			String username = request.getParameter("j_username");
			List<User> user = userService.getUserByLogin(username);
			Md5PasswordEncoder md = new Md5PasswordEncoder();
			if (user != null
					&& !user.isEmpty()
					&& user.get(0).getPassword()
							.equals(md.encodePassword(password, null))) {
				;
				webUserPref.setWebUser(user.get(0));
				String redirectUrl = "/ttn/" + languageBean.getLocale()
						+ "/index.html";
				if (webUserPref.getRedirectUrl() != null
						&& webUserPref.getRedirectUrl().length() > 0) {

					redirectUrl = webUserPref.getRedirectUrl();
				}
				try {
					response.sendRedirect(redirectUrl);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					LOG.error("Error Redirecting to content page "
							+ redirectUrl + " after login", e);
				}
				return null;
			}

		}

		return "login";

	}

}
